<script lang="ts" setup name="StockRealSheetEdit">
import { Minus, Plus } from '@element-plus/icons-vue'
import { FormInstance, FormRules } from 'element-plus'
import { getWaresCategoryListAPI } from '~/src/api/goods'
import { Inventory } from '~/src/api/interface/goods'
import { Procure } from '~/src/api/interface/procure'
import {
  checkStockRealSheetAPI,
  createStockRealSheetAPI,
  createStockRealSheetDetailAPI,
  editStockRealSheetAPI,
  getStockPlanAPI,
  getStockPlanGoodsListAPI,
  getStoreHouseAPI,
} from '~/src/api/procure'
import { useHandleDetail } from '~/src/hooks/useHandleData'
import { stockRealEditColumn } from './info/columns'
import SelectTreeTable from '/library/components/SelectTreeData/index.vue'

const route = useRoute()
const router = useRouter()
const documentStatus = ref('add')
onMounted(async () => {
  documentStatus.value = route.query.type as string
  await onShowStore()
  if (route.query.id) {
    getStockPlanDetail()
  }
})
const getStockPlanDetail = async () => {
  const { data } = await createStockRealSheetDetailAPI({ id: route.query.id })
  stockRealSheetForm.value = JSON.parse(JSON.stringify(data))
  list.value = data.inventorydetailList
  houseIdD.value = data.houseId
}
const houseIdD = ref(0) // 如果是编辑复原仓库是复原数据
const list = ref<Inventory.CheckGoodsList[]>([])
watch(
  () => stockRealSheetForm.value.houseId,
  () => {
    if (houseIdD.value === stockRealSheetForm.value.houseId && route.query.id) {
      stockRealSheetForm.value.inventorydetailList = list.value
    }
  }
)
const ruleFormRef = ref<FormInstance>()
const stockRealSheetForm = ref<Procure.StockRealSheet>({
  orderId: 0,
  orderNo: '',
  range: 1,
  planOrderId: null,
  planOrderNo: null,
  checkerId: 0,
  checkTime: '',
  createTime: '',
  houseId: 0,
  dateType: 0,
  remark: '',
  sysUserId: 0,
  inventorydetailList: [],
})
const planRules = reactive<FormRules>({})

// // 打开库存商品弹出层列表
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null)
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  if (!stockRealSheetForm.value.houseId) return ElMessage.error('请先选择仓库')
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: 'productsId', // 勾选中数据字段
    // 底部选中的数据显示在底部
    selTags: stockRealSheetForm.value?.inventorydetailList
      .filter((age) => age.goodsId !== 0)
      .map((i) => {
        i.name = i.name
        i.id = i.productsId as number
        return i
      }),
    columns: [
      { type: 'selection', width: 80 },
      { prop: 'barcode', label: '编码', align: 'left', width: 200 },
      { prop: 'name', label: '商品名称', align: 'left', minWidth: 220 },
      { prop: 'productName', label: '规格', align: 'left', minWidth: 100 },
      { prop: 'unitName', label: '单位', align: 'left', minWidth: 160 },
      { prop: 'purPrice', label: '采购价格', minWidth: 120 },
    ],
    apiParams: { houseId: stockRealSheetForm.value.houseId, planOrderId: stockRealSheetForm.value.planOrderId },
    idName: 'goodsCategoryId',
    // 发请求
    treeApi: getWaresCategoryListAPI,
    api: getStockPlanGoodsListAPI,
  }
  selectTreeTableRef.value?.acceptParams(params)
}
// // 选中库存商品
const handleSelectedTreeList = (val: any) => {
  console.log(val)
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        name: im.name,
        id: im.id,
        // storeId: im.storeId,
        productsId: im.productsId,
        productName: im.productName,
        goodsId: im.id,
        planQuantity: im.planQuantity,
        price: im.costPrice,
        barcode: im.barcode,
        categoryName: im.categoryName,
        realQuantity: 0,
        costPrice: im.costPrice,
        costAmount: im.costAmount,
        unitName: im.unitName, // 单位
        profitLossQuantity: '',
        profitLossAmount: '',
      }
    })
    list.forEach((v: any) => {
      if (!stockRealSheetForm.value.inventorydetailList.some((i) => i.productsId === v.productsId)) {
        stockRealSheetForm.value.inventorydetailList.push(v)
      }
    })
    console.log(stockRealSheetForm.value.inventorydetailList)
  }
}

// 选择盘点计划单审核 --start--
const dialogVisible = ref(false)
const planList = ref<any>([])
const searchVal = ref('')
const onSelectPlan = () => {
  dialogVisible.value = true
}
// 监听弹出层
watch(
  () => dialogVisible.value,
  async (val) => {
    if (val) {
      if (!stockRealSheetForm.value.houseId) {
        ElMessage.error('请先选择仓库')
        dialogVisible.value = false
      } else {
        const { data } = await getStockPlanAPI({
          orderType: 1,
          pageNum: 1,
          pageSize: 9999,
          // status: 1,
          isDetail: 1,
          houseId: stockRealSheetForm.value.houseId,
          orderNo: searchVal.value,
        })
        planList.value = JSON.parse(JSON.stringify(data.list))
        // console.log(planList.value);
      }
    } else {
      searchVal.value = ''
    }
  }
)

// 监听搜索数据
watch(
  () => searchVal.value,
  async () => {
    if (!dialogVisible.value) return
    const { data } = await getStockPlanAPI({ orderType: 1, pageNum: 1, pageSize: 9999, isDetail: 1, orderNo: searchVal.value })
    planList.value = JSON.parse(JSON.stringify(data.list))
    // console.log(planList.value);
  }
)
// 监听盘点范围
watch(
  () => stockRealSheetForm.value.range,
  (val) => {
    if (val === 1) {
      stockRealSheetForm.value = {
        orderId: 0,
        planOrderId: null,
        orderNo: '',
        range: 1,
        checkerId: 0,
        checkTime: null,
        createTime: '',
        houseId: 0,
        dateType: 0,
        remark: '',
        sysUserId: 0,
        planOrderNo: null,
        inventorydetailList: [],
      }
    }
  }
)

const isPass = ref(false)
const onSubmit = async () => {
  if (stockRealSheetForm.value.inventorydetailList.length < 1) return ElMessage.error('商品明细不能为空')

  // 提示用户是否有0的数据 start
  if (stockRealSheetForm.value.inventorydetailList.some((e) => e.realQuantity === 0)) {
    await ElMessageBox.confirm('商品是否有盘点数量为0', '温馨提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        isPass.value = true
      })
      .catch(() => {
        isPass.value = false
      })
  } else {
    isPass.value = true
  }
  if (!isPass.value) return
  // 提示用户是否有0的数据 end
  if (!route.query?.id) {
    await createStockRealSheetAPI(stockRealSheetForm.value)
    router.push('/procure/stockRealSheet')
  } else {
    await editStockRealSheetAPI(stockRealSheetForm.value)
    router.push('/procure/stockRealSheet')
  }
}

const { useChangeDetailData } = useHandleDetail()
// 保存并审核
const onCheckSubmit = async () => {
  if (stockRealSheetForm.value.inventorydetailList.length < 1) return ElMessage.error('商品明细不能为空')
  // 提示用户是否有0的数据 start
  if (stockRealSheetForm.value.inventorydetailList.some((e) => e.realQuantity === 0)) {
    await ElMessageBox.confirm('商品是否有盘点数量为0', '温馨提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        isPass.value = true
      })
      .catch(() => {
        isPass.value = false
      })
  } else {
    isPass.value = true
  }
  if (!isPass.value) return
  // // 提示用户是否有0的数据 end
  useChangeDetailData(checkStockRealSheetAPI, { ...stockRealSheetForm.value, checkFlag: true }, '/procure/stockRealSheet')
  // await checkStockRealSheetAPI({ ...stockRealSheetForm.value, checkFlag: true })
  // router.push({
  //   path: '/procure/stockRealSheet',
  // })
}

const delSpecRow = (index: number) => {
  if (stockRealSheetForm.value.inventorydetailList.length <= 1) return ElMessage.error('商品不能少于一条数据')
  stockRealSheetForm.value.inventorydetailList.splice(index, 1)
}

/* 仓库start;*/
const storeList = ref<any[]>([])
const onShowStore = async () => {
  const res = await getStoreHouseAPI({ pageSize: 9999, pageNum: 1 })
  storeList.value = res.data.list
  storeList.value.forEach((v) => {
    if (v.isDefault) {
      stockRealSheetForm.value.houseId = v.id
    }
  })
}
const onselectChange = () => {
  // 防止编辑时选择仓库数据不会发生改变
  stockRealSheetForm.value.inventorydetailList = []
}
</script>

<template>
  <div class="auto-height-container flx-column">
    <header-line
      :confirmIsSHow="documentStatus !== 'audited'"
      :title="(route.query.id && +route.query.id ? '编辑' : '新增') + '盘点单'"
      @on-submit="onSubmit()"
    >
      <template #button>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择商品')">添加商品明细</el-button>
        <!-- v-if="stockPlanForm.status === 2"  -->
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="onCheckSubmit">保存并审核</el-button>
      </template>
    </header-line>

    <el-form ref="ruleFormRef" :inline="true" label-width="120px" :model="stockRealSheetForm" :rules="planRules">
      <el-form-item label="单据号" prop="orderNo">
        <el-input v-model="stockRealSheetForm.orderNo" class="width160" disabled placeholder="系统自动生成" />
      </el-form-item>

      <el-form-item label="仓库" prop="houseId">
        <el-select
          v-model="stockRealSheetForm.houseId"
          class="width150"
          :disabled="documentStatus === 'audited'"
          placeholder="请选择仓库"
          @change="onselectChange"
        >
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item v-if="documentStatus === 'add'" label="盘点范围" prop="range">
        <!-- :disabled="documentStatus === 'audited'" -->
        <el-select v-model="stockRealSheetForm.range" class="width150">
          <el-option label="实时盘点" :value="1" />
          <el-option label="计划盘点" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item v-if="documentStatus === 'add' && stockRealSheetForm.range === 2" label="盘点计划" prop="remark" @click="onSelectPlan">
        <el-input v-model="stockRealSheetForm.planOrderNo" disabled style="max-width: 600px">
          <template #append>
            <span style="cursor: pointer">选择单据</span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item v-if="documentStatus !== 'add' && stockRealSheetForm.planOrderNo" label="盘点计划单号" prop="planOrderNo">
        <el-input v-model="stockRealSheetForm.planOrderNo" class="width200" disabled placeholder="请填写" :rows="1" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="stockRealSheetForm.remark" class="width150" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <div class="flex1">
      <pro-table
        ref="proTable"
        :columns="stockRealEditColumn"
        :data="stockRealSheetForm.inventorydetailList"
        :is-card="false"
        :pagination="false"
        row-key="id"
        style="height: 100%"
        :tool-button="documentStatus !== 'audited'"
      >
        <template #realQuantity="{ row }">
          <el-input-number v-model="row.realQuantity" class="w100" :controls="false" :disabled="documentStatus === 'audited'" :min="0" />
        </template>

        <template #operate="scope">
          <!-- <div class="flx-justify-between">
          <el-icon color="#169D82" size="18" @click="openSelectTreeTable('选择商品')"><plus /></el-icon>
          <el-icon color="#f00" size="18" @click="delSpecRow(scope.$index)"><minus /></el-icon>
        </div> -->
          <div v-if="documentStatus !== 'audited'" class="flx-justify-between">
            <el-button :icon="Plus" link type="primary" @click="openSelectTreeTable('选择商品')" />
            <el-button :icon="Minus" link @click="delSpecRow(scope.$index)" />
          </div>
        </template>
      </pro-table>
    </div>
    <select-tree-table ref="selectTreeTableRef" @selected-list="handleSelectedTreeList" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-table thead .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table tfoot .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table .el-table__cell) {
  padding: 0;
}
:deep(.el-form-item) {
  margin-bottom: 8px;
}
</style>
